<?php
namespace ScarecrowCache\lib;
use \Closure;
use ScarecrowCache\lib\core\DbHanlde;
use ScarecrowCache\lib\interfaces\DbHandleAbstract;

class ScarecrowFactory{

	//绑定匿名函数
	private $bindClosure = [];

	//绑定一个对象
	private $bindObject = [];

	public function __construct()
	{
		$this->bind('Cache', function (){
			return new DbHanlde();
		});
	}

	public function bind(string $name, $obj)
	{
		if (empty($name)) {
			return false;
		}

		if ($obj instanceof Closure) {
			$this->bindClosure[$name] = $obj;
		}

		if ($obj instanceof DbHandleAbstract) {
			$this->bindObject[$name] = $obj;
		}
		return true;
	}

	public function delete(string $name)
	{
		unset($this->bindObject[$name]);
		unset($this->bindClosure[$name]);
	}

	public function execute(string $name, $params=[])
	{
		if (array_key_exists($name, $this->bindClosure)) {

			return call_user_func_array($this->bindClosure[$name], $params);
		}

		if (array_key_exists($name, $this->bindObject)) {
			return $this->bindObject[$name];
		}

		return false;
	}

	public function __destruct()
	{
		// TODO: Implement __destruct() method.
		$this->bindClosure = [];
		$this->bindObject = [];
	}
}